package com.bzyd.derby.plugin;

import org.apache.commons.lang3.StringUtils;

/**
 * 分页SQL工具类
 */
public class PageSqlUtil {

    /**
     * 获取分页拼接SQL
     *
     * @param page 分页请求对象
     * @param sql  原SQL
     * @return
     */
    public static String getPageSql(Page page, String sql) {
        StringBuilder sb = new StringBuilder(sql);
        if (StringUtils.isNotBlank(page.getSortBy())) {
            sb.append(" order by ").append(page.getSortBy()).append(" ").append(page.getRank());
        }

        int startIndex = (page.getPageIndex() - 1) * page.getPageSize();
        sb.append(" offset ").append(startIndex).append(" rows fetch next ").append(page.getPageSize()).append(" rows only");
        return sb.toString().toLowerCase();
    }

    /**
     * 获取计数SQL
     *
     * @param sql 原SQL
     * @return
     */
    public static String getCountSql(String sql) {
        StringBuilder sb = new StringBuilder("select count(*) from ( ");
        sb.append(sql).append(" ) a");
        return sb.toString().toLowerCase();
    }
}
